package context

import (
	"encoding/json"
	"fmt"
	"ginadmin/logger"
	"github.com/gin-gonic/gin"
	"io"
)

type M map[string]interface{}

func Write(c *gin.Context, status int, b []byte) {
	logger.Info(string(b))
	c.Writer.WriteHeader(status)
	c.Writer.Write(b)
}

func JSON(c *gin.Context, status int, m map[string]interface{}) {

	w := c.Writer
	w.Header().Set("Content-Type", "application/Json; charset=utf-8")
	w.WriteHeader(status)
	jsonBytes, _ := json.Marshal(m)
	logger.Info(string(jsonBytes))
	w.Write(jsonBytes)
}
func Map(c *gin.Context, m map[string]interface{}) {

	w := c.Writer
	w.Header().Set("Content-Type", "application/Json; charset=utf-8")
	logger.Info(m)
	json.NewEncoder(w).Encode(m)
}

func Result(c *gin.Context, m interface{}) {

	w := c.Writer
	w.Header().Set("Content-Type", "application/Json; charset=utf-8")
	json.NewEncoder(w).Encode(m)
	logger.Info(m)
}
func Err(c *gin.Context, code int32, s string) {

	w := c.Writer
	w.Header().Set("Content-Type", "application/Json; charset=utf-8")
	str := fmt.Sprintf(`{"code": %d, "msg": "%s"}`, code, s)
	logger.Info(str)
	io.WriteString(w, str)
}

func Msg(c *gin.Context, s string) {

	w := c.Writer
	w.Header().Set("Content-Type", "application/Json; charset=utf-8")
	str := fmt.Sprintf(`{"code": 200, "msg": "%s"}`, s)
	logger.Info(str)
	io.WriteString(w, str)
}

func OK(c *gin.Context) {

	w := c.Writer
	w.Header().Set("Content-Type", "application/Json; charset=utf-8")
	//w.WriteHeader(http.StatusOK)
	str := `{"code": 200, "msg": "处理成功"}`
	logger.Info(str)
	io.WriteString(w, str)
}
